package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.mapper.ScoreMapper;
import com.example.demo.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class UpdateScoreController {
    @Autowired
    private  ScoreMapper sm;
    @RequestMapping("/updatescore")
    public void updateScore(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id=Integer.valueOf(request.getParameter("id"));
        String course=request.getParameter("course");
        int flag=sm.findNeedScore(id,course).getFlag();
        try {
            Float escore = Float.valueOf(request.getParameter("escore"));
            Float ascore = Float.valueOf(request.getParameter("ascore"));
            int fscore = Integer.valueOf(request.getParameter("fscore"));
            int ffscore = (int) Math.round(escore * 0.6 + ascore * 0.4);
            if (ffscore == fscore) {
                int n = sm.updateSco(flag, ascore, fscore);
                if (n > 0) {
                    response.getWriter().write(JSONObject.toJSONString(Message.success("Success update!")));
                } else response.getWriter().write(JSONObject.toJSONString(Message.failure("Failure update!")));
            } else
                response.getWriter().write(JSONObject.toJSONString(Message.failure("You input final score is error!")));
        }catch (Exception e){
            response.getWriter().write(JSONObject.toJSONString(Message.failure(e.getMessage())));
        }
    }
}
